package com.lxw.library.views;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import com.lxw.library.R;
import com.lxw.library.utils.DateUtil;
import com.lxw.library.utils.TimeSelector;

import java.text.SimpleDateFormat;
import java.util.Calendar;


/**
 * 作者：李学伟
 * 日期：2018/8/9
 * 用途：
 */

public class LxwDataTimeView extends LxwTextView implements View.OnClickListener {

    private int MODE = 0;//0 标识只显示年月日，1 标识年月日 时分

    public LxwDataTimeView(Context context, int MODE, ColumnRequestListener columnRequestListener) {
        super(context,0, columnRequestListener);
        mView.setOnClickListener(this);
        this.MODE = MODE;
    }

    public LxwDataTimeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    public void onClick(View v) {
        showSelectTime();
    }


    private void showSelectTime() {
        SimpleDateFormat ymdhm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        String currentTime = ymdhm.format(calendar.getTimeInMillis());
        calendar.add(Calendar.YEAR, -5);
        String startDate = ymdhm.format(calendar.getTimeInMillis());

        calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 5);
        String endDate = ymdhm.format(calendar.getTimeInMillis());
        TimeSelector timeSelector = new TimeSelector(mContext, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                long selectTime;
                String showTime;
                if (MODE == 0) {
                    selectTime = DateUtil.parse(time, "yyyy-MM-dd").getTime();
                } else {
                    selectTime = DateUtil.parse(time, "yyyy-MM-dd HH:mm:ss").getTime();
                }

                if (requestListener != null) {
                    boolean result = requestListener.checkTime(paramer, time, selectTime);
                    if (result) {
                        valueTv.setText(time);
                    }
                } else {
                    valueTv.setText(time);
                }
            }
        }, startDate, currentTime, endDate, "", "");
        if (MODE == 0) {
            timeSelector.setMode(TimeSelector.MODE.YMD);//只显示 年月日
        } else {
            timeSelector.setMode(TimeSelector.MODE.YMDHM);//只显示 年月日 时分
        }
        timeSelector.show();
    }

    @Override
    public String getValue() {
        String value = super.getValue();
        if (!TextUtils.isEmpty(value)) {
            value = value.replace("年", "-");
            value = value.replace("月", "-");
            value = value.replace("日", "");
        }
        return value;
    }

}
